import type { Plugin } from "vite"

/**
 * @author 微若蜉蝣
 * @@description 处理项目中导入的 json 文件
 */

export default function (): Plugin {
  return {
    name: "vite-plugin-json",
    enforce: "pre",
    async handleHotUpdate(ctx) {
      const { server } = ctx
      if (ctx.file.includes("essays/index.json")) {
        const defaultRead = ctx.read
        ctx.read = async function () {
          return `export default ${await defaultRead()}`
        }
        server.ws.send({
          type: "custom",
          event: "essays-update",
          data: await defaultRead(),
        })
        return []
      }
    },
  }
}
